import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { formatDate, formatTime } from '../services/storage'

interface SweetMoment {
  id: number
  date: string
  time: string
  title: string
  content: string
  mood: string
  category: 'daily' | 'surprise' | 'conversation' | 'memory'
  emoji: string
}

interface Category {
  id: string
  label: string
  icon: string
}

interface SweetMomentFormProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (moment: SweetMoment | Omit<SweetMoment, 'id'>) => void
  initialData?: SweetMoment | null
  categories: Category[]
}

const moodOptions = [
  { value: 'sweet', label: '甜蜜', color: 'from-pink-400 to-rose-400', emoji: '😘' },
  { value: 'surprised', label: '惊喜', color: 'from-orange-400 to-amber-400', emoji: '😲' },
  { value: 'loving', label: '爱意', color: 'from-red-400 to-pink-400', emoji: '🥰' },
  { value: 'cozy', label: '温馨', color: 'from-yellow-400 to-orange-400', emoji: '🤗' },
  { value: 'romantic', label: '浪漫', color: 'from-purple-400 to-pink-400', emoji: '💕' },
  { value: 'motivated', label: '激励', color: 'from-green-400 to-emerald-400', emoji: '💪' },
  { value: 'happy', label: '开心', color: 'from-blue-400 to-cyan-400', emoji: '😊' },
  { value: 'peaceful', label: '宁静', color: 'from-indigo-400 to-purple-400', emoji: '😌' }
]

export function SweetMomentForm({ isOpen, onClose, onSubmit, initialData, categories }: SweetMomentFormProps) {
  const [formData, setFormData] = useState<{
    title: string
    content: string
    category: 'daily' | 'surprise' | 'conversation' | 'memory'
    mood: string
    emoji: string
    date: string
    time: string
  }>({
    title: '',
    content: '',
    category: 'daily',
    mood: 'sweet',
    emoji: '😘',
    date: formatDate(),
    time: formatTime()
  })

  useEffect(() => {
    if (initialData) {
      setFormData({
        title: initialData.title,
        content: initialData.content,
        category: initialData.category,
        mood: initialData.mood,
        emoji: initialData.emoji,
        date: initialData.date,
        time: initialData.time
      })
    } else {
      setFormData({
        title: '',
        content: '',
        category: 'daily',
        mood: 'sweet',
        emoji: '😘',
        date: formatDate(),
        time: formatTime()
      })
    }
  }, [initialData, isOpen])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!formData.title.trim() || !formData.content.trim()) {
      alert('请填写标题和内容')
      return
    }

    if (initialData) {
      onSubmit({
        ...initialData,
        ...formData
      })
    } else {
      onSubmit(formData)
    }
  }

  const handleMoodChange = (mood: string) => {
    const selectedMood = moodOptions.find(m => m.value === mood)
    setFormData(prev => ({
      ...prev,
      mood,
      emoji: selectedMood?.emoji || '😘'
    }))
  }

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
        >
          <motion.div
            className="bg-white rounded-3xl p-8 max-w-2xl w-full max-h-[90vh] overflow-y-auto"
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.8, opacity: 0 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold text-gray-800">
                {initialData ? '编辑甜蜜时光' : '记录新的甜蜜时光'} ✨
              </h2>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 标题 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  标题 *
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                  placeholder="给这个美好时刻起个名字..."
                  required
                />
              </div>

              {/* 日期和时间 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    日期
                  </label>
                  <input
                    type="date"
                    value={formData.date}
                    onChange={(e) => setFormData(prev => ({ ...prev, date: e.target.value }))}
                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    时间
                  </label>
                  <input
                    type="text"
                    value={formData.time}
                    onChange={(e) => setFormData(prev => ({ ...prev, time: e.target.value }))}
                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                    placeholder="例如：下午 3:20"
                  />
                </div>
              </div>

              {/* 分类 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  分类
                </label>
                <div className="grid grid-cols-2 gap-3">
                  {categories.filter(c => c.id !== 'all').map(category => (
                    <label key={category.id} className="flex items-center space-x-3 cursor-pointer">
                      <input
                        type="radio"
                        name="category"
                        value={category.id}
                        checked={formData.category === category.id}
                        onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value as any }))}
                        className="text-rose-500 focus:ring-rose-400"
                      />
                      <span className="text-lg">{category.icon}</span>
                      <span className="text-gray-700">{category.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* 心情 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  心情
                </label>
                <div className="grid grid-cols-4 gap-3">
                  {moodOptions.map(mood => (
                    <button
                      key={mood.value}
                      type="button"
                      onClick={() => handleMoodChange(mood.value)}
                      className={`p-3 rounded-xl border-2 transition-all ${
                        formData.mood === mood.value
                          ? 'border-rose-400 bg-rose-50'
                          : 'border-gray-200 hover:border-rose-300'
                      }`}
                    >
                      <div className="text-2xl mb-1">{mood.emoji}</div>
                      <div className="text-xs text-gray-600">{mood.label}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 内容 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  内容 *
                </label>
                <textarea
                  value={formData.content}
                  onChange={(e) => setFormData(prev => ({ ...prev, content: e.target.value }))}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400 resize-none"
                  rows={4}
                  placeholder="详细描述这个甜蜜的时刻..."
                  required
                />
              </div>

              {/* 提交按钮 */}
              <div className="flex space-x-4 pt-4">
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-rose-500 to-pink-500 text-white rounded-xl hover:from-rose-600 hover:to-pink-600 transition-all"
                >
                  {initialData ? '保存修改' : '记录时光'} ✨
                </button>
              </div>
            </form>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
